# -*-coding:Utf-8 -* 
""" SZ menu module
"""
import bge, bgl, blf, mathutils, aud, os
from .ressources import *

from .multiUi import *

CORE = bge.core
IN = CORE.inputs
UI = CORE.gui
SZ_Globals = CORE.SZ_Globals

SZ_Globals['MainMenu'] = {}

# Create new layer to add all element for menu
MainScreen.setLayer("menu")

def selectFirstLayer(fl,selection):
	menu = SZ_Globals['MainMenu']
	if selection == 4:
		SZ_Globals['MainMenu']["exit"] = False
		Device.play(backsound)
		MainScreen.hideLayer("exit")
		return
	Device.play(clicsound)
	if selection == 3:
		SZ_Globals['MainMenu']["exit"] = True
		MainScreen.showLayer("exit")
		return
	if menu["selection"][0] != None and menu["selection"][0] != selection:
		fl.buttons[menu["selection"][0]].activate = True
		fl.buttons[menu["selection"][0]].color = None
		menu[1][menu["selection"][0]].visible = False
		menu[1][menu["selection"][0]]._onclic(menu[1][menu["selection"][0]],None)
	if selection == None:
		if menu["selection"][0] != None:
			menu['secondL'].y = "i1.0"
			menu['secondL'].hide(0.2)
			Device.play(backsound)
		menu["selection"][0] = None
		return
	elif menu["selection"][0] == None:
		menu['secondL'].show(0.2)
	if selection < 3:
		menu['secondL'].y = "i"+str(350+(selection*39))
		Device.play(slidesound)
		fl.buttons[selection].activate = False
		fl.buttons[selection].color = bg_button_s
		menu[1][selection].visible = True		
		menu["selection"][0] = selection
	
def selectMap(ml,selection):
	menu = SZ_Globals['MainMenu']
	name = ml.buttons[selection].text
	#SZ_Globals['loading'] = ml.buttons[selection].mapfile
	menu[1][0]._onclic(menu[1][0],None)
	CORE.load.Level.load(name)
	
def selectSolo(sl,selection):
	menu = SZ_Globals['MainMenu']
	if selection == menu["selection"][1]:
		return
	Device.play(clicsound)
	if selection != None:
		sl.buttons[selection].activate = False
		sl.buttons[selection].color = col_border
	if menu["selection"][1] != None:
		sl.buttons[menu["selection"][1]].activate = True
		sl.buttons[menu["selection"][1]].color = None
	if menu["selection"][1] == 4:
		menu[2].parent = None
		menu[2].destroy()
		menu[2] = None
	if selection == 4:
		Device.play(slidesound)
		"""ml = {}
		for aFile in os.listdir(bge.logic.expandPath('//resources/maps')):
			name = os.path.splitext(aFile)
			if name[1] in ('.blend','.szl'):
				print(aFile)
				ml[name[0]] = bge.logic.expandPath('//resources/maps/'+aFile)
		maplist = UI.ButtonList(MainScreen, 635,0,ml.keys(),165,1.0)
		for i in range(0,len(ml)):
			maplist.buttons[i].mapfile = ml[maplist.buttons[i].text]"""
		maplist = UI.ButtonList(MainScreen, 635,0,CORE.load.Level.MapsList(),165,1.0)
		maplist.color = transblack
		maplist.hover_modification["color"] = bg_button
		maplist._onclic = selectMap
		SZ_Globals['MainMenu'][2] = maplist
	menu["selection"][1] = selection
	
	
def selectMulti(sl,selection):
	menu = SZ_Globals['MainMenu']
	if selection == menu["selection"][1]:
		return
	Device.play(clicsound)
	if selection != None:
		sl.buttons[selection].activate = False
		sl.buttons[selection].color = col_border
	if menu["selection"][1] != None:
		sl.buttons[menu["selection"][1]].activate = True
		sl.buttons[menu["selection"][1]].color = None
		
	menu["selection"][1] = selection
	
	if selection == 1:
		thirdL.visible=True
		thirdL.gui.load()
	elif selection==3:
		SZ_Globals['2DScreen'].setLayer("multi_ipConnect")
		mask = UI.Zone(MainScreen,0,0,1.0,1.0)
		mask.color = transblack
		bar = UI.Zone(mask,335,"i350",5,135)
		bar.color = col_border
		textip = UI.TextBox(mask, 348, "i350", "Connexion par IP:")
		textip.text_color = col_border
		textip.size = 28
		textip.font = font
		global ipvalue
		ipvalue = UI.InputField(mask, 348,"i{}".format(360+textip.h), '255.255.255.255', SZ_Globals['MainInputMap'])
		ipvalue.focus()
		buttonsubmit = UI.Button(mask, 540,"i{}".format(355+textip.h),'Connexion')
		buttonsubmit.text_color = col_border
		buttonsubmit.size = 20
		buttonsubmit.font = font
		buttonsubmit.hover_modification["color"] = col_border
		buttonsubmit.hover_modification["text_color"] = black
		buttonsubmit._onclic = multiIpConnect
	elif selection == 4:
		CORE.load.Level.load('qg')
	

def multiIpConnect(params):
	SZ_Globals['2DScreen'].hideLayer("multi_ipConnect")
	thirdL.gui.winServer(ipvalue.getText())

def selectSettings(sl,selection):
	menu = SZ_Globals['MainMenu']
	if selection == menu["selection"][1]:
		return
	Device.play(clicsound)
	if selection != None:
		sl.buttons[selection].activate = False
		sl.buttons[selection].color = col_border
	if menu["selection"][1] != None:
		sl.buttons[menu["selection"][1]].activate = True
		sl.buttons[menu["selection"][1]].color = None
		
	menu["selection"][1] = selection
	
def playHoverSound(blist,button):
	Device.play(hoversound)
	
# Static Elements
bg = UI.Box(MainScreen,0,0,1.0,1.0,background)
logobox = UI.Box(MainScreen,0,-logo.height,logo.width,logo.height,logo)

# Set defaults
UI.ButtonList.DefaultSize = 20
UI.ButtonList.DefaultFont = font
UI.ButtonList.DefaultColor = black
UI.ButtonList.DefaultHovercallback = playHoverSound

# First button layer
firstL = UI.ButtonList(MainScreen, "i-335","i350",("Solo","Multijoueur","Options","Quitter"),335)
firstL.size = 28
firstL.padding = 8
firstL.text_color = white
firstL.DefaultAlignement = 2
firstL.hover_modification["color"] = bg_button
firstL.hover_modification["text_color"] = black
firstLBorder = UI.Box(firstL,1.0,0,5,1.0)
firstLBorder.color = col_border
SZ_Globals['MainMenu'][0] = firstL
firstL._onclic = selectFirstLayer

# Second button layer
secondL = UI.Box(MainScreen, 340, "i1.0",295,1.0)
secondL.color = bg_grey
secondL.visible = False
secondL.anim[1] = CORE.AnimateValue(secondL.y,0.3)
icontop = UI.Box(secondL, .0,1.0,1.0,icon.height,icon)
SZ_Globals['MainMenu']['secondL'] = secondL

# Third zone layer
global thirdL
thirdL = UI.Box(MainScreen, 637, "i"+str(294), bge.render.getWindowWidth()-637, bge.render.getWindowHeight()-294)
thirdL.color = transblack
thirdL.visible = False
thirdL.gui=MultiStructUi(thirdL, UI, SZ_Globals)
SZ_Globals['MainMenu']['thirdL'] = thirdL

UI.ButtonList.DefaultAlignement = 1
UI.ButtonList.DefaultPadding = (6,6,6,6)
UI.ButtonList.DefaultHover["color"] = col_border

soloPanel = UI.ButtonList(secondL, 0,"i0",("Continuer","Commencer","Sauver","Charger","Carte perso"),1.0)
soloPanel.visible = False
soloPanel._onclic = selectSolo
multiPanel = UI.ButtonList(secondL, 0,"i0",("Partie rapide","Chercher partie","Local","Connexion par IP", "DevMap"),1.0)
multiPanel.visible = False
multiPanel._onclic = selectMulti
settingPanel = UI.ButtonList(secondL, 0,"i0",("Générale","Vidéo","Audio","Contrôle"),1.0)
settingPanel.visible = False
settingPanel._onclic = selectSettings
SZ_Globals['MainMenu'][1] = (soloPanel,multiPanel,settingPanel)

UI.ButtonList.DefaultColor = white

SZ_Globals['MainMenu']["selection"] = [None,None,None]
SZ_Globals['MainMenu']["exit"] = False


SZ_Globals['2DScreen'].setLayer("exit")

def SelectExit(ebl, select):
	if select == 1:
		CORE.exitgame()
	else:
		selectFirstLayer(SZ_Globals['MainMenu'][0],4)

mask = UI.Zone(MainScreen,0,0,1.0,1.0)
mask.color = transblack
bar = UI.Zone(mask,335,"i350",5,135)
bar.color = col_border
textexit = UI.TextBox(mask, 348, "i350", "Êtes-vous sûr de vouloir quitter ?")
textexit.text_color = col_border
textexit.size = 28
textexit.font = font
buttonexit = UI.ButtonList(mask, 348,"i400",("Non","Oui"),100)
buttonexit.text_color = col_border
buttonexit.size = 28
buttonexit.font = font
buttonexit.hover_modification["color"] = col_border
buttonexit.hover_modification["text_color"] = black
buttonexit._onclic = SelectExit

MainScreen.setLayer()
#SZ_Globals['2DScreen'].setLayer()

def escapeAction(active):
	if active:
		return
	if SZ_Globals['MainMenu']["exit"] == True:
		selectFirstLayer(SZ_Globals['MainMenu'][0],4)
		return
	if SZ_Globals['state'] == "InGame":
		CORE.setState("EscMenu")
		return
	elif SZ_Globals['state'] == "EscMenu":
		CORE.setState("InGame")
		return

escapeKey = IN.Input(SZ_Globals['MainInputMap'],bge.events.ESCKEY)
escapeKey.addAct(escapeAction)

def openMenu(pre_state,post_state):
	if post_state == "MainMenu":
		bge.logic.addScene('menu', 0)
		"""if 'MainMenuMusic' not in SZ_Globals and os.path.isfile(bge.logic.expandPath('//resources/musics/main_menu.mp3')):
			factory = aud.Factory(bge.logic.expandPath('//resources/musics/main_menu.mp3'))
			SZ_Globals['MainMenuMusic'] = SZ_Globals['AU_Device'].play(factory),factory
			SZ_Globals['MainMenuMusic'][0].loop_count = -1
			"""
	MainScreen.showLayer("menu")
	IN.MouseTracking().show()
	
def closeMenu(pre_state,post_state):
	if pre_state == "MainMenu":
		for aScene in bge.logic.getSceneList():
			if aScene.name == 'menu':
				aScene.end()
	if 'MainMenuMusic' in SZ_Globals:
		SZ_Globals['MainMenuMusic'][0].stop()
		del SZ_Globals['MainMenuMusic']
	MainScreen.hideLayer("menu")
	IN.MouseTracking().hide()

SZ_Globals["state_func"]["MainMenu"] = (openMenu,closeMenu)
SZ_Globals["state_func"]["EscMenu"] = (openMenu,closeMenu)


